using System.Web;
using Tools.Common.UnitOfWork.Contracts;
using System;

namespace Web.App.Infrastructure.UnitOfWork
{
    public class UnitOfWork
    {
        private const string UNIT_OF_WORK = "Application.UnitOfWork.Current";
        [ThreadStatic] private static IUnitOfWork unitOfWork;

        public static IUnitOfWork Current
        {
            get
            {
                if(RunsInWebContext)
                    return HttpContext.Current.Items[UNIT_OF_WORK] as IUnitOfWork;
                return unitOfWork;
            }

            internal set
            {
                if (RunsInWebContext)
                    HttpContext.Current.Items[UNIT_OF_WORK] = value;
                else
                    unitOfWork = value;
            }
        }

        private static bool RunsInWebContext
        {
            get { return HttpContext.Current != null; }
        }

        public static IUoWSession AsSession
        {
            get
            {
                if(RunsInWebContext)
                    return HttpContext.Current.Items[UNIT_OF_WORK] as IUoWSession;
                return unitOfWork as IUoWSession;
            }
        }
    }
}